package com.tiancheng.onecode.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.tiancheng.onecode.configuration.MiniAppProperties;
import com.tiancheng.onecode.entity.Platform;
import com.tiancheng.onecode.enums.MiniAppTypeEnum;
import com.tiancheng.onecode.exception.Asserts;
import com.tiancheng.onecode.model.dto.MerchantRegistrationQrDTO;
import com.tiancheng.onecode.model.dto.MinioUploadDto;
import com.tiancheng.onecode.model.response.ApplicationAccessTokenResponseVO;
import com.tiancheng.onecode.model.response.Result;
import com.tiancheng.onecode.service.IQrService;
import com.tiancheng.onecode.service.IUploadService;
import com.tiancheng.onecode.trade.TradeCache;
import com.tiancheng.onecode.trade.utils.ForestHttpUtil;
import com.tiancheng.onecode.utils.DateTimeUtil;
import com.tiancheng.onecode.utils.JsonUtil;
import com.tiancheng.onecode.utils.ServiceLocator;
import com.tiancheng.onecode.utils.WxHttpUtils;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.message.BasicHeader;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: kellen
 * @Description: 二维码管理 service impl
 * @Date: create in 2024/12/27 11:27
 */
@Service
public class QrServiceImpl implements IQrService {

    @Resource
    private IUploadService uploadService;

    @Resource
    private MiniAppProperties miniAppProperties;

    @Override
    public MerchantRegistrationQrDTO genMerchantRegistrationQr(Platform platform) {
        final MiniAppProperties.MiniAppInfo miniAppInfo = miniAppProperties.getMiniAppInfo(platform.getPlatformCode(), MiniAppTypeEnum.wechat_b);
        String wechatAccessToken = TradeCache.getWechatAccessToken(miniAppInfo.getAppid());
        if (StringUtils.isEmpty(wechatAccessToken)) {
            // 没有token
            final Map<String, String> params = new HashMap<>();
            params.put("grant_type", "client_credential");
            params.put("appid", miniAppInfo.getAppid());
            params.put("secret", miniAppInfo.getSecret());
            final String response = ForestHttpUtil.getInstance().get("https://api.weixin.qq.com/cgi-bin/token", params, null);
            if (StringUtils.isNotEmpty(response)) {
                final Map result = JsonUtil.fromJson(response, Map.class);
                if (null != result) {
                    wechatAccessToken = MapUtils.getString(result, "access_token");
                    final Long expiresIn = MapUtils.getLong(result, "expires_in");
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(wechatAccessToken) && Objects.nonNull(expiresIn)) {
                        TradeCache.cacheWechatAccessToken(miniAppInfo.getAppid(), wechatAccessToken, expiresIn);
                    }
                }
            }
            Asserts.isTrue(StringUtils.isNotEmpty(wechatAccessToken), "获取微信认证token失败");
        }
        final JSONObject pageParams = new JSONObject();
        pageParams.put("path", "pages/auth/nav?appkey=onecode_merchant&platform_code=" + platform.getPlatformCode());
        String envVersion = "trial";
        if (ServiceLocator.getEnvironment().equals("prod")) {
            envVersion = "release";
        }
        pageParams.put("env_version", envVersion);
        // 生成二维码
        final byte[] imgContent = WxHttpUtils.doWXPost("https://api.weixin.qq.com/wxa/getwxacode?access_token=" + wechatAccessToken, pageParams);
        if (null != imgContent) {
            final MinioUploadDto minioUploadDto = uploadService.minioUploadImg(platform.getPlatformName() + "-商户进件(" + DateTimeUtil.getCurrentDateTime() + ").png", imgContent);
            if (null != minioUploadDto) {
                final MerchantRegistrationQrDTO d = new MerchantRegistrationQrDTO();
                d.setUrl(minioUploadDto.getUrl());
                d.setName(minioUploadDto.getName());
                return d;
            }
        }
        return null;
    }

    @Override
    public MerchantRegistrationQrDTO merchantPayQr() {
        return null;
    }
}
